import React, { useState, useEffect } from "react";
import Taro, { getCurrentInstance, useReachBottom } from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtActivityIndicator } from "taro-ui";
import Card from "../../../component/Card";
import NullState from "../../../component/NullState";
import { searchArticles } from "./api";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/activity-indicator.scss";
import "taro-ui/dist/style/components/loading.scss";
import css from "./index.module.less";

export default function Index() {
  const { value, uuid } = getCurrentInstance().router.params;
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(6);
  const [articleData, setArticleData] = useState([]);
  const [loadingArticles, setLoadingArticles] = useState(true);
  useEffect(() => {
    setLoadingArticles(true);
    searchArticles(value, uuid, page, size).then((res) => {
      if (res.code === 200) {
        setArticleData([...res.data]);
        setLoadingArticles(false);
      }
    });
  }, []);
  const detail = (uuid, liked) => {
    Taro.navigateTo({ url: `../detail/index?uuid=${uuid}&liked=${liked}` });
  };
  useReachBottom(() => {
    const currentPage = page + 1;
    setPage(currentPage);
    searchArticles(value, uuid, currentPage, size).then((res) => {
      if (res.code === 200) {
        setArticleData([...articleData, ...res.data]);
      }
    });
  });
  return (
    <React.Fragment>
      <View className={css.content}>
        <AtActivityIndicator
          content="加载中..."
          isOpened={loadingArticles}
        ></AtActivityIndicator>
        {loadingArticles ? (
          ""
        ) : articleData.length === 0 ? (
          <NullState />
        ) : (
          <View className={css.card}>
            {articleData.map((result) => {
              return (
                <View onClick={() => detail(result.article.uuid, result.liked)}>
                  <Card {...result} />
                </View>
              );
            })}
          </View>
        )}
      </View>
    </React.Fragment>
  );
}
